﻿using HalconDotNet;
using HWindow_Tool.Control;
using LD.Host;
using LD.Vision;
using System;
using System.Collections.Generic;

namespace LD.Tool
{
    [Tool(FrmParam = "ToolBarcode2DFrm", Text = "二维码识别", ToolType = ToolEnum.Vision)]
    class ToolBarcode2D : BaseTool
    {
        public override OpResult Execute(TB_Tool model)
        {
            try
            {
                stopwatch.Start();
                if (model.Param != null)
                {
                    var _param = Newtonsoft.Json.JsonConvert.DeserializeObject<ToolBarcode2DParam>(model.Param);
                    if (!string.IsNullOrEmpty(_param.ImageSource))
                    {
                        HImage img = (HImage)base.GetToolValue(model, _param.ImageSource);
                        if (img != null)
                        {
                            HDataCode2D hDataCode2D = new HDataCode2D();
                            hDataCode2D.CreateDataCode2dModel(_param.symbolType, _param.genParamName, _param.genParamValue);
                            var xld = hDataCode2D.FindDataCode2d(img, "train", "all", out var resultHandles, out var decodedDataStrings);
                            HWindow_Final hwindow = null;
                            if (!string.IsNullOrEmpty(_param.CameraName) && FrmVisionMain.Instance.HWindow.ContainsKey(_param.CameraName))
                            {
                                hwindow = FrmVisionMain.Instance.HWindow[_param.CameraName];
                                
                                hwindow.DispObj(xld,"green");
                            }
                            if (decodedDataStrings != null && decodedDataStrings.Length >= 1)
                            {
                                条码 = decodedDataStrings.ToString().Replace("\"", "");
                                hwindow.DispText(条码, "green");
                                isSuccess = true;
                                Log(model, $"条码:{条码}", LogLevel.一般);
                            }
                            else
                            {
                                Log(model, "条码无法识别", LogLevel.警告);
                                isSuccess = false;
                            }

                            //释放资源
                            hDataCode2D.Dispose();
                        }
                        else
                            Log(model, "图像不能为空", LogLevel.严重);
                    }
                    else
                        Log(model, "图像不能为空", LogLevel.严重);
                }
            }
            catch (Exception ex)
            {
                Log(model, ex.Message, LogLevel.严重);
            }
            finally
            {
                stopwatch.Stop();
            }
            return new OpResult() { IsSuccess = isSuccess, Message = message, ExecuteTime = stopwatch.ElapsedMilliseconds };
        }
        [Tool(Output = true)]
        public string 条码 { get; set; }
    }
}
